<?php
namespace app\home\controller;

use app\common\controller\HomeBase;
use app\common\model\User as UserModel;
use app\common\model\FundLog as FundModel;
use think\Db;
use think\Config;


/**
 * 用户
 * Class User
 */
class User extends HomeBase
{
    protected function _initialize()
    {
        parent::_initialize();
        $this->getMenu();
        if(session('uid'))
        {
            $uid = session('uid');
            $user_info = db('user')
                            ->alias('u')
                            ->where("u.id", $uid)
                            ->join('user_rank ur','u.rank_id = ur.id')
                            ->field('u.*,ur.rank_name,ur.reg_money')
                            ->find();             
            $this->user_info = $user_info;
            session('user_info',$user_info);             // 保存到session
            $this->uid = $user_info['id'];
            $this->assign('user_info',$user_info);       // 存储用户信息
            $this->assign('uid',$this->uid);             // 用户id
        }else{
            $this->redirect('home/index/login');
        }
        $this->user_model = new UserModel();
    }
    /**
     * 底部菜单赋值
     */
    protected function getMenu()
    {
        $menu = 'user';
        $this->assign('menu', $menu);
    }
    /**
     * 用户中心首页
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }
    /**
     * 退出登录
     * @return mixed
     */
    public function logout(){
        session('uid',null);
        $this->redirect('home/index/index');
        exit;
    }
    /**
     * 转账
     * @return mixed
     */
    public function transfer(){
        $post_url = url('Home/User/do_transfer');
        return $this->fetch('transfer',['post_url' => $post_url]);
    }
    /**
     * 推荐记录
     * @return mixed
     */
    public function shareUser(){                                     
        // 获取用户充值记录
        $list = db('user')
                ->where("share_id = $this->uid ")
                ->order('id DESC')
                ->paginate(15, true);
        return $this->fetch('share_user',['list' => $list]);
    }
    /**
     * 转账记录
     * @return mixed
     */
    public function transferList(){
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                      
        $change_type = change_type();                                       
        // 获取用户充值记录
        $list = db('transfer')
                ->alias('t')
                ->join('user u','u.id = t.in_uid')
                ->field('u.user_name,t.*')
                ->where("t.out_uid = $this->uid ")
                ->order('t.id DESC')
                ->paginate(15, true);
        //p($list);die;
        return $this->fetch('transfer_list',['list' => $list,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 转账记录详情
     * @param int    $id 记录的id
     * @return mixed
     */
    public function transferInfo($id='')
    { 
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                      
        $change_type = change_type();  
        $map['uid']  = ['=', $this->uid];
        $map['id']   = ['=', $id];
        $info = db('transfer')
                ->alias('t')
                ->join('user u','u.id = t.in_uid')
                ->field('u.user_name,t.*')
                ->where("t.out_uid = $this->uid ")
                ->find();
        //p($info);die;
        if (!$info) {
            $this->error('记录不存在!');
        }
        return $this->fetch('transfer_info',['info' => $info,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 提交转账
     * @return mixed
     */
    public function do_transfer(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证规则
            $validate = validate('Transfer');              
            // 验证数据
            if(!$validate->check($data)){
                // 验证错误提示       
                show(0,$validate->getError());          
            }else{
                // 获取转入账户信息
                $in_user_info = db('user')->where(" user_name =  '".$data['name']."' ")->find();
                if ($data['name'] == $this->user_info['user_name']) {
                    show(0,'不能给自己转账！');
                }
                // 会员只能转账会员，商户只能转账商户
                if ($this->user_info['rank_id'] < 7) { // 会员
                    if ($in_user_info['rank_id'] > 6) {
                        show(0,'会员不能给商户转账！');
                    }
                }else{                                  // 商户
                    if ($in_user_info['rank_id'] < 7) {
                        show(0,'商户不能给会员转账！');
                    }
                }
                // 已释放激活积分
                if ($data['wallet_type'] == '2') {
                    $type_name = 're_reg_integral';
                // 已释放消费积分
                }elseif ($data['wallet_type'] == '4') {
                    $type_name = 're_consume_integral';
                // 已释放分享积分
                }elseif ($data['wallet_type'] == '6') {
                    $type_name = 're_share_integral';
                }else{
                    show(0,'钱包类型错误！');
                }
                // 满十个积分可以使用
                if ($this->user_info[$type_name] < 10 ) {
                    show(0,'钱包必须满10个积分！');
                }
                // 判断钱包是否充足
                if ($this->user_info[$type_name] < $data['money']) {
                    show(0,'钱包余额不足！');
                }
                // 更新转出会员钱包
                $up_user[$type_name] = $this->user_info[$type_name] - $data['money'];
                // 更新转入会员
                $up_in_user[$type_name] = $in_user_info[$type_name] + $data['money'];
                // 写入转账记录
                $transfer_log[] = array(
                                'num'           => $data['money'],
                                'wallet_type'   => $data['wallet_type'],
                                'time'          => time(),
                                'in_uid'        => $in_user_info['id'],
                                'out_uid'       => $this->uid,
                            );
                // 转出记录
                $log[] =  array(
                                'num'           => '-'.$data['money'],
                                'wallet_type'   => $data['wallet_type'],
                                'change_type'   => '2',// 2类型为转出
                                'time'          => time(),
                                'uid'           => $this->uid,
                                'before_num'    => $this->user_info[$type_name],
                                'later_num'     => $up_user[$type_name],
                                'description'   => '转账给'.$data['name']."：".$data['money'],
                            );
                // 转入记录
                $log[] =  array(
                                'num'           => $data['money'],
                                'wallet_type'   => $data['wallet_type'],
                                'change_type'   => '3',// 类型为转入
                                'time'          => time(),
                                'uid'           => $in_user_info['id'],
                                'before_num'    => $in_user_info[$type_name],
                                'later_num'     => $up_in_user[$type_name],
                                'description'   => "会员：".$this->user_info['user_name'].'给你转账'.$data['money'],
                            );

                Db::startTrans();

                // 更新转出会员
                $up_user_res = model('user')->allowField(true)->save($up_user,['id' => $this->uid]);
                // 更新转入会员
                $up_in_user_res = model('user')->allowField(true)->save($up_in_user,['id' => $in_user_info['id']]);
                // 插入资金记录
                $log_res = model('fund_log')->saveAll($log);
                // 插入转账记录
                $transfer_log_res = model('transfer')->saveAll($transfer_log);

                if ($up_user_res && $up_in_user_res && $log_res && $transfer_log_res) {
                    Db::commit();
                    show(0,'转账成功！',url('Home/User/financeList'));
                }else{
                    Db::rollback();
                    show(0,'转账失败！');
                }
            }
        }
    }
    /**
     * 会员升级等级
     * @return mixed
     */
    public function chooseRank()
    {
        $rank_list = db('user_rank')->field('id,rank_name')->where('id','>',$this->user_info['rank_id'])->select();      //会员等级列表
        return $this->fetch('choose_rank',['rank_list' => $rank_list]);
    }
    /**
     * 具体会员等级
     * @param  int $rank_id 升级等级
     * @return mixed
     */
    public function rankPay($rank_id='')
    {
        $rank_list = db('user_rank')->field('id,rank_name,reg_money')->where('id','>',$this->user_info['rank_id'])->select();      //会员等级列表
        //$post_url = url('Home/User/upGrade');
        $post_url = url('Home/User/upGradePay');
        return $this->fetch('rank_pay',['rank_list' => $rank_list,'rank_id' => $rank_id,'post_url' => $post_url]);
    }

    /**
     * 增值宝在线充值
     * @return mixed
     */
    public function payForBalance()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 金额判断
            if (!isMoney($data['money'])) {
                $this->error('金额错误');
            }
            // 获取支付地址和订单id  // ($uid,$money,$type)
            $payinfo = controller('Payment')->getPayInfo($this->uid,$data['money'],'1');
            // 支付结果异步轮询
            $post_url = url('Home/Payment/check_ajax');
            // 二维码支付页面赋值
            $re_url = url('Home/Payment/pay_code')."?url=".$payinfo['data']['url']."&order_id=".$payinfo['order_id'];
            $this->redirect($re_url);
        }
    }
    /**
     * 等级升级在线支付
     * @return mixed
     */
    public function upGradePayPost()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 要升级到该等级的信息
            $up_rank_info = db('user_rank')->where('id',$data['rank_id'])->field('reg_money,reg_integral,rank_name')->find();
            // 目前等级信息 
            $now_rank_info = db('user_rank')->where('id',$this->user_info['rank_id'])->field('reg_money,reg_integral,rank_name')->find();
            // 升级到现在等级所交金额
            $up_money = $up_rank_info['reg_money'] - $now_rank_info['reg_money'];


            // 获取支付地址和订单id  // ($uid,$money,$type)
            $payinfo = controller('Payment')->getPayInfo($this->uid,$up_money,'2',$data['rank_id']);
            // 支付结果异步轮询
            $post_url = url('Home/Payment/check_ajax');
            // 二维码支付页面赋值
            $re_url = url('Home/Payment/pay_code')."?url=".$payinfo['data']['url']."&order_id=".$payinfo['order_id'];
            $this->redirect($re_url);
        }
    }

    /**
     * 充值记录
     * @return mixed
     */
    public function payList()
    {
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                      
        $change_type = change_type();                                       
        // 获取用户充值记录
        $list = db('fund_log')
                ->where("uid = $this->uid and change_type = '1' or change_type = '13' ")
                ->order('id DESC')
                ->paginate(15, true);
        return $this->fetch('pay_list',['list' => $list,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 充值记录详情
     * @param int    $id 记录的id
     * @return mixed
     */
    public function payInfo($id='')
    { 
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                      
        $change_type = change_type();  
        $map['uid']  = ['=', $this->uid];
        $map['id']   = ['=', $id];
        $info = db('fund_log')
                ->where($map)
                ->find();
        if (!$info) {
            $this->error('记录不存在!');
        }
        return $this->fetch('pay_info',['info' => $info,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 用户资料修改
     * @return mixed
     */
    public function userInfo()
    { 
        if ($this->request->isPost()) {
            // 表单提交的数据
            $data = $this->request->post();
            // 修改昵称
            if ($data['user_name'] !== $this->user_info['user_name']) {
                //$this->user_model->save(['user_name'  => $data['user_name']],['id' => $this->uid]);
                $new_user['user_name'] = $data['user_name'];
            //是否修改密码
            }elseif (!$data['old_pwd'] && !$data['new_pwd'] && !$data['re_new_pwd']) {
                show(0,'请输入要修改的内容！');
            // 修改密码
            }else{
                // 是否输入原来密码
                if (!$data['old_pwd']) {
                    show(0,'请输入原来的密码！');
                // 判断密码是否正确
                }elseif ($this->user_info['password'] !== md5($data['old_pwd'] . Config::get('salt'))) {
                    show(0,'原始密码错误！');
                // 判断新密码是否正确
                }elseif(!$data['new_pwd'] || strlen($data['new_pwd']) < 6) {
                    show(0,'请输入6位新密码！');
                // 判断重复新密码是否一致
                }elseif($data['re_new_pwd'] !== $data['new_pwd']) {
                    show(0,'两次密码输入不一致！');
                // 赋值新密码
                }else{
                    $new_user['password'] = md5($data['new_pwd'] . Config::get('salt'));
                }
            }
            // 修改用户资料
            $res = $this->user_model->save($new_user,['id' => $this->uid]);
            if ($res) {
                show(1,'修改成功',url('Home/User/index'));
            }else{
                show(0,'修改失败');
            }
        }
        // 提交地址
        $post_url = url('Home/User/userInfo');
        return $this->fetch('user_info', ['post_url' => $post_url]);
    }


    /**
     * 用户手机
     * @return mixed
     */
    public function changeMobile()
    { 
        if ($this->request->isPost()) {
            // 表单提交的数据
            $data = $this->request->post();
            // 验证规则
            $validate = validate('ChangeMobile');              
            // 验证数据
            if(!$validate->check($data)){
                // 验证错误提示       
                show(0,$validate->getError());          
            }else{
                // 判断手机号
                if ($data['mobile'] == $this->user_info['mobile']) {
                    show(0,'不能与原号码相同！');
                // 判断发送短信的手机号是否一致
                }elseif ($data['mobile'] !== session('change_mobile')) {
                    show(0,'手机号码已改变请重新操作！');
                // 验证码判断
                }elseif ((int)$data['code'] !== session('change_code')) {
                    show(0,'验证码错误！');
                }else{
                    $res = $this->user_model->save(['mobile' => $data['mobile']],['id' => $this->uid]);
                    if ($res) {
                        show(1,'修改成功',url('Home/User/userInfo'));
                    }else{
                        show(0,'修改失败');
                    }
                }
            }
            
        }
        // 提交地址
        $post_url = url('Home/User/changeMobile');
        return $this->fetch('change_mobile', ['post_url' => $post_url]);
    }

    /**
     * 扫码
     * @return mixed
     */
    public function set_up()
    { 
        return $this->fetch('set_up');
    }
    /**
     * 收钱二维码
     * @return mixed
     */
    public function collectCode()
    {   
        // 商户等级才有收钱码
        if ($this->user_info['rank_id'] < 7) {
            $this->redirect('Home/User/Index');
        }
        // 获取商户设置金额
        $pay_money = session('pay')?session('pay'):'100';
        // 包含具体收钱金额
        //$url = $_SERVER['SERVER_NAME'].url('Home/User/payFor','uid='.session('uid').'&pay='.$pay_money);// 收钱地址
        // 不包含具体收钱金额
        $url = "http://".$_SERVER['SERVER_NAME'].url('Home/User/payFor','uid='.session('uid'));// 收钱地址
        //P($url);die;
        return $this->fetch('collect_code', ['url' => $url,'pay_money' => $pay_money]);
    }
    /**
     * 设置收款金额
     * @return mixed
     */
    public function setMoney()
    { 
        // 表单提交地址
        $post_url = url('Home/User/doSetMoney');
        return $this->fetch('set_money',['post_url' => $post_url]);
    }
    /**
     * 提交设置收款金额
     * @return mixed
     */
    public function doSetMoney()
    { 
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (isNum($data['num'])) {
                session('pay',$data['num']);
                show(1,'设置成功！',url('Home/User/collectCode'));
            }else{
                show(0,'数据类型错误！');
            }
        }
    }
    /**
     * 钱包
     * @return mixed
     */
    public function waitingRelease($type)
    {
        // 待释放激活积分
        if ($type == 'reg_integral') {
            $info['name'] = '待释放激活积分'; 
        // 待释放消费积分
        }elseif ($type == 'consume_integral') {
            $info['name'] = '待释放消费积分'; 
        // 待释放分享积分
        }elseif ($type == 'share_integral') {
            $info['name'] = '待释放分享积分'; 
        }
        $info['num'] = $this->user_info[$type];
        return $this->fetch('waiting_release',['info' => $info]);
    }
    /**
     * 提现
     * @return mixed
     */
    public function withdrawal()
    { 
        if ($this->request->isPost()) {
            // 表单提交的数据
            $data = $this->request->post();
            // 验证规则
            $validate = validate('Withdrawal');   
            // 验证数据
            if(!$validate->check($data)){
                // 验证错误提示       
                show(0,$validate->getError());          
            }else{
                // 增值宝提现
                if ($data['wallet_type'] == '7') {
                    $type_name = 'balance';
                // 商户钱包提现
                }elseif($data['wallet_type'] == '8'){
                    $type_name = 'shop_money';
                }else{
                    show(0,'钱包类型错误！');
                }
                if ($this->user_info[$type_name] < $data['put_money']) {
                    show(0,'钱包余额不足！');
                }
                // 更新钱包会员信息
                $up_user[$type_name] = $this->user_info[$type_name] - $data['put_money'];
                // 会员提现记录
                $log[]  =  array(
                                'num'           => '-'.$data['put_money'],
                                'wallet_type'   => $data['wallet_type'],
                                'change_type'   => '6',
                                'time'          => time(),
                                'uid'           => $this->uid,
                                'before_num'    => $this->user_info[$type_name],
                                'later_num'     => $up_user[$type_name],
                                'description'   => '提现：'.$data['put_money'],
                            );
                // 提现银行卡
                $bank_info = db('bank')->where("uid = {$this->uid} and id = {$data['bank_id']}")->find();
                if (!$bank_info) {
                    show(0,'提现银行错误！');
                }
                $put_log[]  =  array(
                                'num'           => $data['put_money'],
                                'wallet_type'   => $data['wallet_type'],
                                'time'          => time(),
                                'uid'           => $this->uid,
                                'bank_name'     => $bank_info['bank_name'],
                                'card_id'       => $bank_info['card_id'],
                                'true_name'     => $bank_info['true_name'],
                                'mobile'        => $bank_info['mobile'],
                            );
                Db::startTrans();
                $up_user_res = model('user')->allowField(true)->save($up_user,['id' => $this->uid]);
                // 插入资金记录
                $log_res = model('fund_log')->saveAll($log);
                // 插入提现记录
                $put_log_res = model('extract')->saveAll($put_log);
                if ($up_user_res && $log_res &&  $put_log_res) {
                    Db::commit();
                    show(1,'提交成功！',url('Home/User/financeList'));
                }else{
                    Db::rollback();
                    show(0,'提交失败！');
                }
                p($log);die;
            }
            show(0,'提现');
            p($data);die;
        }
        // 查找改用户的提现银行卡
        $list = db('bank')
                ->where("uid = $this->uid and status = 1")
                ->select();
        // 表单提交地址
        $post_url = url('Home/User/withdrawal');
        // 明天日期
        $tomorrow['month'] = date("m",strtotime("+1 day"));
        $tomorrow['day']   = date("d",strtotime("+1 day"));
        return $this->fetch('withdrawal',['list' => $list,'post_url' => $post_url,'tomorrow' => $tomorrow]);
    }
    /**
     * 充值
     * @return mixed
     */
    public function top_up()
    {   // 明天日期
        $yesterday = date("Y-m-d",strtotime("+1 day"));
        $post_url = url('home/user/payForBalance');
        return $this->fetch('top_up',['post_url' => $post_url,'yesterday' => $yesterday]);
    }
    
    /**
     * 已释放
     * @return mixed
     */
    public function alreadyRelease($type)
    {
        // 已释放激活积分
        if ($type == 're_reg_integral') {
            $info['name'] = '已释放激活积分';
        // 已释放消费积分 
        }elseif ($type == 're_consume_integral') {
            $info['name'] = '已释放消费积分'; 
         // 已释放分享积分 
        }elseif ($type == 're_share_integral') {
            $info['name'] = '已释放分享积分'; 
        }
        $info['num'] = $this->user_info[$type];
        return $this->fetch('already_release',['info' => $info]);
    }
    /**
     * 商家钱包
     * @return mixed
     */
    public function shopWallet()
    { 
        return $this->fetch('shop_wallet');
    }
    /**
     * 商家钱包明细
     * @return mixed
     */
    public function shopFundList()
    {
        $map['uid']         = ['=', $this->uid];
        $map['wallet_type'] = ['=', '8'];
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                      
        $change_type = change_type();                                       
        // 获取用户资金记录
        $list = db('fund_log')
                ->where($map)
                ->order('id DESC')
                ->paginate(15, true);
        return $this->fetch('shop_fund_list',['list' => $list,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 收支详情
     * @param int    $id 记录的id
     * @return mixed
     */
    public function shopFundInfo($id='')
    { 
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                      
        $change_type = change_type();  
        $map['uid']  = ['=', $this->uid];
        $map['id']   = ['=', $id];
        $info = db('fund_log')
                ->where($map)
                ->find();
        if (!$info) {
            $this->error('记录不存在!');
        }
        return $this->fetch('shop_fund_info',['info' => $info,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 增值宝
     * @return mixed
     */
    public function balance()
    {
        // 昨天时间戳范围
        $begin_yesterday = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $end_yesterday   = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        // 统计昨日收益
        $yesterday_income = db('fund_log')
                            ->where("time > $begin_yesterday and time < $end_yesterday and change_type = 9 and uid = $this->uid")
                            ->value('num');
        $yesterday_income = $yesterday_income?$yesterday_income:'0';
        // 统计所有收益
        $all_income =   db('fund_log')
                        ->where("change_type = 9 and uid = $this->uid")
                        ->value('sum(num)');
        $all_income = $all_income?$all_income:'0';
        // 增值宝累计支出
        $all_expend =   db('fund_log')
                        ->where("wallet_type = 7 and uid = $this->uid and num < 0")
                        ->value('sum(num)');
        $all_expend = $all_expend?$all_expend:'0';
        return $this->fetch('balance',['yesterday_income' => $yesterday_income,'all_income' => $all_income,'all_expend' => $all_expend,'rate' => $this->proConfig['balance_ratio']]);
    }
    /**
     * 提现记录
     * @return mixed
     */
    public function withdrawList()
    {
        $map['uid']         = ['=', $this->uid];
        //$map['wallet_type'] = ['=', '8'];
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                      
        $change_type = change_type();                                       
        // 获取用户资金记录
        $list = db('extract')
                ->where($map)
                ->order('id DESC')
                ->paginate(15, true);
        return $this->fetch('withdraw_list',['list' => $list,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 提现记录明细
     * @param int    $id 记录的id
     * @return mixed
     */
    public function withdrawInfo($id='')
    {
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                   transfer   
        $change_type = change_type();  
        $map['uid']  = ['=', $this->uid];
        $map['id']   = ['=', $id];
        $info = db('extract')
                ->where($map)
                ->find();
        //p($info);die;
        return $this->fetch('withdraw_info',['info' => $info,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 财务
     * @param int    $page
     * @return mixed
     */
    public function financeList($page = 1,$date='')
    {
        if (strtotime($date)) {
            $begin = strtotime($date);// 开始时间
            $end = strtotime($date)+3600*24;// 结束时间
            $map['time'] = array('between',"$begin,$end");// 条件查询
            $this->assign('date',$date);// 日期赋值
            $this->assign('day',date('d', $begin));// 日期赋值
            $this->assign('month',(int)date('m', $begin));// 日期赋值
        }
        $map['uid'] = ['=', $this->uid];
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                      
        $change_type = change_type();                                       
        // 获取用户资金记录
        $list = db('fund_log')
                ->where($map)
                ->order('id DESC')
                ->paginate(15, true);
        return $this->fetch('finance_list',['list' => $list,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 财务明细
     * @param int    $id 记录的id
     * @return mixed
     */
    public function fundInfo($id='')
    {
        // 获取钱包类型
        $wallet_type = wallet_type();
        // 获取操作类型                                      
        $change_type = change_type();  
        $map['uid']  = ['=', $this->uid];
        $map['id']   = ['=', $id];
        $info = db('fund_log')
                ->where($map)
                ->find();
        return $this->fetch('fund_info',['info' => $info,'change_type' => $change_type,'wallet_type' => $wallet_type]);
    }
    /**
     * 奖金
     * @return mixed
     */
    public function bonus()
    {
        // 推荐奖金 商家营业额奖金 
        $list = db('fund_log')
                ->where("uid = $this->uid and change_type = 10 or change_type = 11 ")
                ->order('id DESC')
                ->paginate(15, true);
        return $this->fetch('bonus',['list' => $list]);
    }
    /**
     * 添加银行卡
     * @return mixed
     */
    public function addCard()
    { 
        if ($this->request->isPost()) {
            // 表单提交的数据
            $data = $this->request->post();
            // 验证规则
            $validate = validate('AddCard');   
            // 验证数据
            if(!$validate->check($data)){
                // 验证错误提示       
                show(0,$validate->getError());          
            }else{
                $data['time'] = time();
                $data['uid']  = $this->uid;
                $res = model('bank')->save($data);
                if ($res) {
                    show(1,'添加银行卡成功',url('Home/User/withdrawal'));
                }else{
                    show(0,'添加银行卡失败');
                }
            }
        }
        // 表单提交地址
        $post_url = url('Home/User/addCard');
        return $this->fetch('add_card',['post_url' => $post_url]);
    }
    /**
     * 我的推荐
     * @return mixed
     */
    public function share()
    {
        $share_url = "http://".$_SERVER['SERVER_NAME'].url('Home/Index/reg','share_id='.session('uid'));// 分享注册地址
        return $this->fetch('share', ['share_url' => $share_url]);
    }
    /**
     * 向商户付款
     * @param int $uid 商户id
     * @return mixed
     */
    // 包含收款金额
    //public function payFor($uid,$pay)
    // 不包含收款金额
    public function payFor($uid)
    { 
        // 收款者信息
        $pay_user = db('user')->field("user_name,rank_id")->where("id = $uid")->find();
        // 判断收款人是否存在
        if (!$pay_user) {
            $this->error('收款人不存在！');
        }else{
            // 收款人是否是商户
            if ($pay_user['rank_id'] < '7') {
            //if ($pay_user['rank_id'] < 0) {
                $this->error('收款对象不是商户！');
            }else{

            }
        }
        // 表单提交地址
        $post_url = url('Home/User/doPayFor');
        //return $this->fetch('pay_for',['pay_user' =>$pay_user,'pay_money' => $pay]);
        return $this->fetch('pay_for',['pay_user' =>$pay_user,'post_url' => $post_url,'uid' => $uid]);
    }

    /**
     * 向商户付款
     * @return mixed
     */
    public function doPayFor()
    { 
        if ($this->request->isPost()) {
            // 表单提交的数据
            $data = $this->request->post();
            // 验证规则
            $validate = validate('PayFor');   
            // 验证数据
            if(!$validate->check($data)){
                // 验证错误提示       
                show(0,$validate->getError());          
            }else{


                // 更新会员钱包
                if ($data['type'] == '2') {
                    $type_name = 're_reg_integral';
                }elseif ($data['type'] == '4') {
                    $type_name = 're_consume_integral';
                }elseif ($data['type'] == '6') {
                    $type_name = 're_share_integral';
                }elseif ($data['type'] == '7') {
                    $type_name = 'balance';
                }elseif ($data['type'] == '100') {// 在线扫码支付
                    //show(0,'在线支付');
                    // 获取支付地址和订单id  // ($uid,$money,$type)
                    $payinfo = controller('Payment')->getPayInfo($this->uid,$data['money'],'3','0',$data['pay_uid']);// 3类型为线下扫码支付
                    // 支付结果异步轮询
                    $post_url = url('Home/Payment/check_ajax');
                    // 二维码支付页面赋值
                    $re_url = url('Home/Payment/pay_code')."?url=".$payinfo['data']['url']."&order_id=".$payinfo['order_id'];
                    show(100,'二维码支付',$re_url);
                }else{
                    show(0,'钱包类型错误！');
                }
                if ($type_name !== 'balance') {
                    if ($this->user_info[$type_name] < 10 ) {
                        show(0,'钱包必须满10个积分！');
                    }
                }
                
                if ($this->user_info[$type_name] < $data['money']) {
                    show(0,'钱包余额不足！');
                }


                // 用户等级信息
                $rank_info = db('user_rank')->where('id',$this->user_info['rank_id'])->find();
                // 商户信息
                $shop_info = db('user')->where('id',$data['pay_uid'])->field("user_name,shop_money")->find();
                // 今天时间戳范围
                $begin_today = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $end_today   = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
                if ($type_name !== 'balance') {
                    // 今天消费总金额
                    $today_num = model('fund_log')->where(" uid = {$this->uid} and change_type = 5 and time > $begin_today and time < $end_today")->sum('num');
                    // 消费总金额
                    $all_num = model('fund_log')->where(" uid = {$this->uid} and change_type = 5 ")->sum('num');
                    if ($this->user_info['rank_id'] == '1' && $this->user_info['share_level']) {
                        // 推荐50人
                        if ($this->user_info['share_level'] == '1') {
                            $day_limit = $this->proConfig['fifty_day'];
                            $sum_limit = $this->proConfig['fifty_total'];
                        }
                        // 推荐100人
                        if ($this->user_info['share_level'] == '2') {
                            $day_limit = $this->proConfig['hundred_day'];
                            $sum_limit = $this->proConfig['hundred_total'];
                        }
                        // 判断重消日封顶
                        if ((abs($today_num) + $data['money']) > $day_limit) {
                            // 超出限额
                            show(0,"超出日限额，今日限额剩余".($day_limit-abs($today_num)));
                        }
                        
                        // 判断重消总封顶
                        if ((abs($all_num) + $data['money']) > $sum_limit) {
                            // 超出限额
                            show(0,"超出总限额，总限额剩余".($sum_limit-abs($all_num)));
                        }
                    }else{
                        // 判断重消日封顶
                        if ((abs($today_num) + $data['money']) > $rank_info['day_consume']) {
                            // 超出限额
                            show(0,"超出日限额，今日限额剩余".($rank_info['day_consume']-abs($today_num)));
                        }
                        
                        // 判断重消总封顶
                        if ((abs($all_num) + $data['money']) > $rank_info['sum_consume']) {
                            // 超出限额
                            show(0,"超出总限额，总限额剩余".($rank_info['sum_consume']-abs($all_num)));
                        }
                    }   
                }




                // 推荐商户提成
                // 获取商户推荐人
                $share_id = db('user')->where("id = {$data['pay_uid']}")->value('share_id');
                // 存在商户推荐人
                if ($share_id > 0) {
                    // 推荐提成
                    $bonus = sprintf("%.2f", $this->proConfig['consume_share_ratio']*$data['money']);
                    // 获取推荐人信息
                    $share_user_info = db('user')->where("id = {$share_id}")->find();
                    if ($bonus > 0) {
                        $up_share_user['share_integral'] = $share_user_info['share_integral'] + $bonus;
                        // 推荐人记录
                        $log[] =  array(
                                        'num'           => $bonus,
                                        'wallet_type'   => '5',
                                        'change_type'   => '11',
                                        'time'          => time(),
                                        'uid'           => $share_id,
                                        'before_num'    => $share_user_info['share_integral'],
                                        'later_num'     => $up_share_user['share_integral'],
                                        'description'   => '商户：'.$shop_info['user_name']."消费收款".$data['money'].",分享奖励：".$bonus,
                                    );
                        
                    }
                }

                // 更新会员
                $up_user[$type_name] = $this->user_info[$type_name] - $data['money'];
                // 重消钱包更新会员
                $up_user['consume_integral'] = $this->user_info['consume_integral'] + $data['money'];
                // 更新商家钱包
                $up_shop['shop_money'] = $shop_info['shop_money'] + $data['money'];
                // 会员重消记录
                $log[] =  array(
                                'num'           => $data['money'],
                                'wallet_type'   => '3',
                                'change_type'   => '14',
                                'time'          => time(),
                                'uid'           => $this->uid,
                                'before_num'    => $this->user_info['consume_integral'],
                                'later_num'     => $up_user['consume_integral'],
                                'description'   => '线下扫码支付：'.$data['money'].'，赠送重消积分：'.$data['money'],
                            );
                // 会员记录
                $log[] =  array(
                                'num'           => '-'.$data['money'],
                                'wallet_type'   => $data['type'],
                                'change_type'   => '5',
                                'time'          => time(),
                                'uid'           => $this->uid,
                                'before_num'    => $this->user_info[$type_name],
                                'later_num'     => $up_user[$type_name],
                                'description'   => '线下扫码支付：'.$data['money'].'，商户：'.$shop_info['user_name'],
                            );
                // 商户记录
                $log[] =  array(
                                'num'           => $data['money'],
                                'wallet_type'   => '8',
                                'change_type'   => '4',
                                'time'          => time(),
                                'uid'           => $data['pay_uid'],
                                'before_num'    => $shop_info['shop_money'],
                                'later_num'     => $up_shop['shop_money'],
                                'description'   => '扫码收钱：'.$data['money'].'，会员：'.$this->user_info['user_name'],
                            );
                // 线下消费记录
                $shop_log = array(
                                'num'           => $data['money'],
                                'wallet_type'   => $data['type'],
                                'time'          => time(),
                                'buy_uid'       => $this->uid,
                                'shop_uid'      => $data['pay_uid'],
                            );
                Db::startTrans();
                // 更新推荐人
                if ($share_id > 0) {
                    if ($bonus > 0) {
                        $up_share_res = model('user')->allowField(true)->save($up_share_user,['id' => $share_id]);
                    }
                }
                
                // 更新会员账号
                $up_user_res = model('user')->allowField(true)->save($up_user,['id' => $this->uid]);
                // 更新商户账号
                $up_shop_res = model('user')->allowField(true)->save($up_shop,['id' => $data['pay_uid']]);
                // 插入资金记录
                $log_res = model('fund_log')->saveAll($log);
                // 插入线下消费记录
                $shop_log_res = model('shop')->save($shop_log);

                if ($up_user_res && $up_shop_res && $log_res && $shop_log_res) {
                    //Db::rollback();
                    Db::commit();
                    show(1,'支付成功！',url('Home/User/financeList'));
                }else{
                    Db::rollback();
                    show(0,'支付失败！');
                }
            }
        }
    }
}
